package hrc.tool.net;

import java.util.Date;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailSender {
	private static MailSender sender;
	private EmailConfig config;
	private MailSender(){
		
	}
	public MailSender(EmailConfig config){
		this.config=config;
	}
	public static MailSender createMailSender(){
		if(sender==null){
			sender=new MailSender();
		}
		return sender;
	}
	public EmailConfig getEmailConfig(){
		return config;
	}
	public boolean send(String toWho, String title, String content) {
		try {
			Properties props = new Properties();
			props.put("mail.smtp.host",config.getMailServer());
			props.put("mail.smtp.auth", "true");
			Session s = Session.getInstance(props);
			MimeMessage message = new MimeMessage(s);
			InternetAddress from = new InternetAddress(config.getAddress());
			message.setFrom(from);
			InternetAddress to = new InternetAddress(toWho);
			message.setRecipient(Message.RecipientType.TO, to);
		
			message.setSubject(title);
			message.setContent(content, "text/html;charset=gbk");
			message.setSentDate(new Date());
			message.saveChanges();
			Transport transport = s.getTransport("smtp");
			transport.connect(config.getMailServer(), config.getAccount(),config.getPassword());
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	public static class EmailConfig {
		private  String address;
		private  String password;
		public EmailConfig(String address,String password){
			this.address=address;
			this.password=password;
		}		
		public void setPassword(String mailPassword) {
			this.password = mailPassword;
		}
		public String getAddress() {
			return address;
		}
		public String getAccount() {
			return address.split("@")[0];
		}
		public String getPassword() {
			return password;
		}
		public String getMailServer() {
			return "smtp."+address.split("@")[1];
		}
	}
}
